<?php

namespace Frieza\Modules\Circle\Controllers;

use App\Http\Controllers\Controller;
use App\Pockets\GridDataModel as pGridDataModel;
use Doraemon\model\Circle\CircleBaseInfo;
use Doraemon\model\Circle\CircleOperationLog as mCircleOperationLog;
use Doraemon\service\Circle\CircleOperationLog;
use Doraemon\tools\Hhzurl;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Illuminate\Http\Request;

class CircleOperationLogController extends Controller
{
    //内容管理
    public function index(Content $content, Request $request): Content
    {
        $userModel = config('admin.database.users_model');
        //圈子信息
        $circleName = CircleBaseInfo::getNameId();

        $page = $request->input('page', 1);
        $pageSize = $request->input('per_page', 20);
        $limit = [($page - 1) * $pageSize, $pageSize];
        $where = $this->buildWhere($request->all());
        $res = CircleOperationLog::getList($where, $limit);

        $gridModel = new pGridDataModel($res['list'], $res['total'], [
            'perPage' => $pageSize,
        ]);

        $listGrid = Admin::grid($gridModel, function (Grid $grid) use ($circleName, $userModel) {
            $grid->disableExport();
            $grid->disableRowSelector();
            $grid->disableCreateButton();
            $grid->expandFilter();

            $grid->filter(function (Grid\Filter $filter) use ($circleName, $userModel) {
                $filter->disableIdFilter();
                $filter->expand();
                $filter->column(1 / 3, function ($filter) use ($circleName) {
                    $filter->equal('circle_id', '圈子名称:')->select($circleName);
                });
                $filter->column(1 / 3, function ($filter) use ($circleName, $userModel) {
                    $filter->equal('admin_name', '后台运营名称:')->select($userModel::all()->pluck('name', 'id'));
                });
                $filter->column(1 / 3, function ($filter) use ($circleName) {
                    $filter->dropDown('source', [
                        'reception' => '圈委ID',
                    ]);
                });
            });

            $grid->column('circle_id', '圈子名称')->display(function () use ($circleName) {
                return $circleName[$this->circle_id] ?? '';
            });

            $grid->column('admin_id', 'uid')->display(function () {
                return $this->admin_info['uid'] ?? '';
            });
            $grid->column('', '昵称')->display(function () {
                if (mCircleOperationLog::SOURCE_RECEPTION == $this->source) {
                    return $this->admin_info['nick'] ?? '';
                }
                return Admin::user()->find($this->admin_id)->name ?? '';
            });
            $grid->column('addtime', '操作时间')->display(function ($addtime) {
                return date('Y-m-d H:i:s', $addtime);
            });
            $url = Hhzurl::getDomain();
            Admin::script($this->setScript($url));
            $grid->actions(function ($actions) {

                $actions->row->setKeyName('id');
                $actions->disableDelete();
                // 去掉编辑
                $actions->disableEdit();
                // 去掉查看
                $actions->disableView();
                $event = mCircleOperationLog::EVENT_MAP[$actions->row['event']];
                $title = $actions->row['photos_info']['title'] ?? '';
                $title = (mb_strlen($title) <= 10) ? mb_substr($title, 0, 9) : mb_substr($title, 0, 9) . "...";
                $jump = "(id:<a class='grid-preview' data-photos_id='{$actions->row['photos_id']}'>{$actions->row['photos_id']}</a>)";
                if (in_array($actions->row['event'], mCircleOperationLog::USER_INFO_MAP)) {
                    $title = $actions->row['user_info']['nick'] ?? '';
                    $jump = "(uid:<a href='/admin/user/Detail/" . $actions->row['author_id'] . "' target='_blank'>{$actions->row['author_id']}</a>)";
                }
                $color = 'red';
                if (empty($title)) {
                    $title = '[无标题]';
                    $color = 'black';
                }
                $event = $event . "(<span style='color: {$color}'>{$title}</span>)";
                $actions->prepend("<p>{$event}{$jump}</p>");
            });
        });
        return $content
            ->header('圈子管理日志')
            ->breadcrumb(['text' => '圈子管理日志', 'url' => '/admin/circle/photos/list'])
            ->body($listGrid);
    }

    public function setScript($url)
    {
        return <<<SCRIPT
        $('.grid-preview').unbind('click').click(function() {
            var photos_id = $(this).attr('data-photos_id');
            var url = '{$url}/tupian/' + photos_id + '.html';
            console.log(url);
            layer.open({
                type: 2,
                title: '搜索结果',
                shadeClose: true,
                shade: 0,
                maxmin: true,
                area: ['400px', '700px'],
                content: url,
            });
		});
SCRIPT;
    }

    public function buildWhere($param)
    {
        if (!empty($param['circle_id'])) {//圈子搜索
            $where['circle_id'] = $param['circle_id'];
        }
        if (!empty($param['admin_name'])) {//运营昵称搜索
            $where['source'] = mCircleOperationLog::SOURCE_ADMIN;
            $where['admin_id'] = $param['admin_name'];
        }
        if (!empty($param['admin'])) {//运营id
            $where['source'] = mCircleOperationLog::SOURCE_ADMIN;
            $where['admin_id'] = $param['admin'];
        }
        if (!empty($param['reception'])) {//圈委id
            $where['source'] = mCircleOperationLog::SOURCE_RECEPTION;
            $where['admin_id'] = $param['reception'];
        }

        return $where ?? [];
    }
}